import { Table, Spin } from 'antd';
import React, { useEffect, useRef, useState, useContext, useMemo } from 'react';
import { Button, Space, Flex, Avatar, Image, Tabs, message } from 'antd';
import { StarFilled, StarOutlined, CloudUploadOutlined, ArrowLeftOutlined } from '@ant-design/icons';
import { ChatContext } from '@/app/chat-context';
import { logoUrl, operateFile } from '@/utils';
import { useTranslation } from 'react-i18next';
import { useTableData, excelParamsInit } from '@/hooks/tableHooks';
import { useRequest } from 'ahooks'
import {
  editExcelFile,
  readExcelFile,
  download_file,
} from '@/client/api'
import { debounce } from 'lodash';
const getDirectoryLabel = (type?: string) => {
  switch (type) {
    case 'recent':
      return '最近';
    case 'favorite':
      return '收藏';
    case 'myDocuments':
      return '我的文档';
    case 'recycleBin':
      return '回收站';
    default:
      return '我的文档';
  }
};
interface ExcelDetailProps {
  record: any,
  onBack: () => void; // 返回按钮的回调函数
  collapsed: boolean;
  collectionFile: (id: string) => void;
  collectionCancelFile: (id: string) => void;
}
const ExcelDetail: React.FC<ExcelDetailProps> = ({ record, onBack, collapsed, collectionFile, collectionCancelFile, }) => {
  const { t } = useTranslation();
  const { excelParams, setExcelParams, excelData, setExcelData, tableType, setTableType } = useTableData();

  console.log("ExcelDetail excelData:", excelData);
  console.log("文件信息", record)
  const { mode, userInfo } = useContext(ChatContext);


  const { run: download_fileRun } = useRequest(
    async () => {
      return await download_file({ id: record.id, })
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        operateFile(res.data, record.file_name.split('.')[0], '.xlsx', false)
      },
      onError: (error: any) => {
        message.error('下载失败');
      }
    }
  )
  const [activeKey, setActiveKey] = useState('');
  const [items, setItems] = useState([]);
  const [loading, setLoading] = useState(false); // 添加 loading 状态
  const currentSheet: any = useMemo(() => {
    return items.find((item: any) => item.key == activeKey);
  }, [items, activeKey,]);
  const onChange = (newActiveKey: string) => {
    setActiveKey(newActiveKey);
    const obj: any = { ...excelParamsInit }
    delete obj.sheet_name;
    setExcelParams(v => {
      return {
        ...v,
        ...obj
      }
    })
  };
  useEffect(() => {
     console.log('tableD322323ata', excelData)
    const _items = ((excelData?.sheet_names || []) as any)?.map((item: any, index: number) => ({
      label: item,
      key: index,
      closable: false,
    }))
    setItems(_items);
    if (_items?.length && (activeKey == '' || activeKey == null)) {
      setActiveKey(_items[0].key)
    }

  }, [excelData,record.id]);

  const [more, setMore] = useState(true);
  // 读取文件
  const { run: readFile, loading: loadingFile } = useRequest(
    async () => {
      if (!record.id || !currentSheet?.label) return;
      return await readExcelFile({
        ...excelParams,
        id: record.id,
        sheet_name:record.sheetName?.length&&!activeKey?record.sheetName[0]:currentSheet?.label,
      });
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        const { data } = res.data || {};

        if (data) {
          setExcelData({
            headers: (data.headers || []).map(i => {
              const key = i.field ?? i.title;
              return {
                title: key,
                dataIndex: key,
                key,
                ellipsis: true,
                width: 150,
              }
            }),
            data: (data.data || []).map(i => {
              return {
                ...i,
                key: i._index_
              }
            }),
            sheet_names: data.sheet_names || [],
          });

          if (data?.data?.length < excelParams.page_size) {
            setMore(false);
          } else {
            setMore(true);
          }
        }
      },
    }
  );

  useEffect(() => {
    readFile();
  }, [activeKey, excelParams?.sheet_name,record.sheetName]);


  const handleTableScroll = debounce((event: Event) => {
    const target = event.target as HTMLElement;
    const scrollTop = target.scrollTop;
    const scrollHeight = target.scrollHeight;
    const clientHeight = target.clientHeight;

    // 仅在纵向滚动时触发
    if (scrollTop + clientHeight >= scrollHeight - 50 && !loading && more) {
      const newPage = excelParams.page + 1;
      setLoading(true);
      readExcelFile({
        ...excelParams,
        page: newPage,
        id: record.id,
        sheet_name: currentSheet?.label,
      })
        .then((res: any) => {
          const ary = res?.data?.data?.data || [];
          if (ary?.length) {
            setExcelData((prev) => ({
              ...prev,
              data: [...(prev.data || []), ...ary.map((i: any) => ({
                ...i,
                key: i._index_,
              }))],
            }));
            setExcelParams((prev) => ({
              ...prev,
              page: newPage,
            }));
            if (ary?.length < excelParams.page_size) {
              setMore(false);
            }
          } else {
            setMore(false);
            console.log('No more data to load.');
          }
        })
        .catch((error) => {
          console.error('Error loading data:', error);
        })
        .finally(() => {
          setLoading(false);
        });
    }
  }, 300); // 防抖时间设置为 300ms

  return (
    <div className='excelDetail w-full h-full border-r border-borderColor dark:border-darkBorderColor flex-auto flex overflow-auto'>
      <div className='w-full h-full bg-[#fff] dark:bg-theme-dark-container p-3'>
        <Flex justify='space-between' align='center' className='w-full h-[40px]'>
          <Space>
            <Button shape="circle" type='text' className='w-full' icon={<ArrowLeftOutlined />} onClick={onBack}></Button>
            <Space>
              <span>{getDirectoryLabel(record?.directoryType as string)}</span>
              <span>&gt;</span>
              <span className='font-bold'>{record?.file_name}</span>
            </Space>
            <StarOutlined onClick={() => {
              if (!record.id) return;
              if (record.collection == 1) {
                collectionCancelFile(record.id)
              } else {
                collectionFile(record.id)
              }
            }}
              className='ml-3 cursor-pointer' style={{
                color: record.collection == 1 ? '#E6A23C' :
                  mode == 'dark' ? 'rgba(255,255,255,0.85)' : 'black',
              }} />
            <CloudUploadOutlined className='ml-3 text-gray-600' />
            <span className='text-gray-600'>已保存于{record.create_time}</span>
          </Space>
          <Space>
            {/* <Button type='link' className='text-[#9F5CFF]' onClick={() => setCopilotVisible(true)}>
                                  <Image src='/chat-excel/ai-copilot.png' preview={false} />
                                  Copilot
                              </Button> */}
            <Space align='center'>
              <Avatar className='bg-slate-400' src={userInfo?.avatar_id ? logoUrl + userInfo.avatar_id : '/ai/user.png'} />
              <span className='whitespace-nowrap overflow-hidden text-ellipsis w-24'>{userInfo?.nick_name}</span>
            </Space>
          </Space>
        </Flex>


        <div style={{ width: collapsed ? '86vw' : '71.5vw' }} className={` mr-1 flex flex-col overflow-scroll flex-auto`}>
          <Flex justify='space-between' align='center' className='w-full p-3 h-[70px] rounded-md bg-[#efeeee] dark:bg-black mt-2 mb-2'>
            <Space>
              {/* <Button>{t('history_version')}</Button> */}
              <Button onClick={async () => {
                download_fileRun();
              }} className='ml-2'>{t('export')}
              </Button>
            </Space>
          </Flex>

          <Table
            bordered={true}
            columns={excelData.headers || []}
            dataSource={excelData.data || []}
            loading={loading || loadingFile}
            pagination={false}
            scroll={{
              x: 'max-content',
              y: 'calc(100vh - 300px)',
            }}
            onScroll={(event) => handleTableScroll(event.nativeEvent)} // 仅监听纵向滚动
          />
          <Tabs
            className='p-2'
            type="editable-card"
            hideAdd={true}
            onChange={onChange}
            activeKey={activeKey}
            items={items}
          />
        </div>
      </div>
    </div>

  );
};

export default ExcelDetail;